<?php

namespace admin\controllers;

use common\helpers\OssHelper;
use common\helpers\OssUrlHelper;
use common\models\Setting;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\UploadedFile;

class SystemController extends Controller
{
    public function actionIndex()
    {
        $type = Yii::$app->request->get('type'); 
        $params = Yii::$app->params['setting_params'];
        $titles = isset($params[$type]) ? $params[$type] : $params['site'];

        $settings = Setting::find()
            ->where(['title' => $titles])
            ->all();

        if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
            foreach ($settings as $setting) {
                $setting->save(false);
            }

            Yii::$app->session->setFlash('updated', 1);

            return $this->redirect(['index', 'type' => $type]);
        }
        
        return $this->render('index', [
            'settings' => $settings
        ]);
    }
    
    public function actionIcon()
    {
        $model = Setting::findOne(['title' => 'site_icon']);
        if (Yii::$app->request->isPost) {
            // 上传文件
            $file = UploadedFile::getInstance($model, 'value');
            if ($file) {
                $filename = md5($file->name . time()) . '.' . $file->extension;
                $oss  = new OssHelper();
                if (!$oss->uploadFile($file->tempName, $filename)) {
                    $model->addError('content', '文件上传失败，请稍后再试');
                    return $this->render('icon', [
                        'model' => $model
                    ]);
                }

                $model->value = $filename;
                $model->save();
            }
        }

        if ($model->value) {
            $model->value = OssUrlHelper::set($model->value);
        }
        return $this->render('icon', [
            'model' => $model
        ]);
    }
}
